﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Threading;
using MicroTest_Client;
using MicroTest.Properties;

namespace MicroTest
{
    public partial class FrmPrepare : Form
    {


        /// <summary>
        /// 主界面是的书写小窗口集合，以点阵笔序列号为键值
        /// </summary>
        private Dictionary<string, BindLable> statusWindows;
        /// <summary>
        /// 点阵笔总数，已连接的点阵笔数，断开连接的点阵笔数
        /// </summary>
        private int All=0, Conn=0, Disconn=0;
        /// <summary>
        /// 是否正在导出数据 
        /// </summary>
        public bool IsExporting = false;

        
        /// <summary>
        /// 是否是落笔状态
        /// </summary>
        private bool IsPenDown = false;
        /// <summary>
        /// 笔序列号与学生姓名的对应的字典
        /// </summary>
        private Dictionary<string, string> studentListDic;
        /// <summary>
        /// 笔列表
        /// </summary>
        private Dictionary<string, PenItem> penItemList;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmPrepare()
        {
            InitializeComponent();
            statusWindows = new Dictionary<string, BindLable>();
            this.WindowState = FormWindowState.Maximized;
            studentListDic = new Dictionary<string, string>();
            //InitControl();
            labBJ.Text = Program.MTInfo.MicroTestRoomInfo;
            Program.StudentInfo.Class= Program.MTInfo.MicroTestRoomInfo;
            penItemList = new Dictionary<string, PenItem>();

        }
        /// <summary>
        /// 载入已绑定名单
        /// </summary>
        private void LoadPenItemList()
        {
            foreach (var item in Program.StudentInfo.BandList)
            {
                PenItem pi = new PenItem();
                pi.PenSerial = item.PenSerial;
                pi.NormalImage = Resources.pen_ico_link;
                pi.DisableImage = Resources.pen_ico_fail;
                pi.DisconectedImage = Resources.pen_ico_fail;
                //pi.ChangePenStatus(PenStatus.Normal);
                pi.SetName(item.Name);
                
                //pi.SelectedColor = Color.FromArgb(226, 175, 134);
               pi.ChangePenStatus(PenStatus.Disabled);
                pi.ClickPen += Pi_ClickPen;
                studentListDic.Add(item.PenSerial, item.Name);
                penItemList.Add(item.PenSerial, pi);
                flpPenlist.Controls.Add(pi);
            }
        }
        /// <summary>
        /// 载入已绑定名单
        /// </summary>
        private void LoadBindItemWindws()
        {
            foreach (var stu in studentListDic)
            {
                string penSerial = stu.Key;
                BindLable bl = new BindLable(penSerial);
                bl.BindStudent(stu.Value);
                statusWindows.Add(penSerial, bl);
                bl.OnMenuEvent += Bl_OnMenuEvent;
                bl.Margin = new Padding(20, 10, 20, 10);
                flpClient.Controls.Add(bl);

            }


        }
        /// <summary>
        /// 删除绑定操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="arg"></param>
        private void Bl_OnMenuEvent(object sender, MenuEventArgs arg)
        {
            BindLable bl = sender as BindLable;
            string penserial = bl.GetPenSerial();
            if(bl.IsBind())
            {
                All--;
                UpdateCountStatus();
            }
            RemoveBindPen(penserial);
            
        }
        /// <summary>
        /// 初始化签到名单列表
        /// </summary>
        private void InitPrepare()
        {
            if(FrmSwhich.SwhichFrm.GetSceneType()==SceneType.Scene_Prepare)
            {
                btnBindAndBacktoScene.Visible = false;
                btnSave.Visible = true;
                btnExt.Visible = true;
            }
            else if(FrmSwhich.SwhichFrm.GetSceneType()==SceneType.Scene_ExamPrepare)
            {
                btnBindAndBacktoScene.NormalImage = Resources.btn_back_to_scene_exam_normal;
                btnBindAndBacktoScene.DownImage = Resources.btn_back_to_scene_exam_press;
                btnBindAndBacktoScene.HoverImage = Resources.btn_back_to_scene_exam_hover;
                btnBindAndBacktoScene.Visible = true;

                btnSave.Visible = false;
                btnExt.Visible = false;
            }
            else if(FrmSwhich.SwhichFrm.GetSceneType()==SceneType.Scene_ClassPrepare)
            {
                btnBindAndBacktoScene.NormalImage = Resources.btn_back_to_scene_class_normal;
                btnBindAndBacktoScene.DownImage = Resources.btn_back_to_scene_class_press;
                btnBindAndBacktoScene.HoverImage = Resources.btn_back_to_scene_class_hover;
                btnBindAndBacktoScene.Visible = true;
                btnSave.Visible = false;
                btnExt.Visible = false;
            }
            LoadPenItemList();
            LoadBindItemWindws();
            All = studentListDic.Count;
            UpdateCountStatus();
        }
        
        
        /// <summary>
        /// 保存绑定文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSave_Click(object sender, EventArgs e)
        {
            if(studentListDic.Count==0)
            {
                MessageBox.Show("学生尚未绑定！","维思课堂",MessageBoxButtons.OK,MessageBoxIcon.Information);
                ELogger.Trace("学生尚未绑定！");
                return;
            }
            Program.StudentInfo.ClearBindInfo();
            foreach (var item in studentListDic)
            {
               StudentCard sc= Program.MTInfo.GetStudentCardByName(item.Value);
                Program.StudentInfo.AddBandInfo(item.Key, sc);
            }
            Program.StudentInfo.Class = Program.MTInfo.MicroTestRoomInfo;
            string folder=Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            folder = folder + "\\BindInfo";
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            string bindData = string.Format("{0}\\{1}.cla",folder,Program.StudentInfo.Class);


            if (File.Exists(bindData))
                File.Delete(bindData);
            bool ret=SerializeHelper.SerialData(bindData, Program.StudentInfo);
            if(ret)
            {
                MessageBox.Show(string.Format("【{0}】学生名单绑定成功！", Program.StudentInfo.Class), "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ELogger.Trace(string.Format("存储学生名单成功！{0} {1}个学生", Program.StudentInfo.Class, Program.StudentInfo.BandList.Count));
            }
            else
            {
                MessageBox.Show(string.Format("存储{0}学生信息失败！", Program.StudentInfo.Class), "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);

                ELogger.Trace("存储学生名单失败");
            }
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExit_Click(object sender, EventArgs e)
        {
            if(DialogResult.OK==MessageBox.Show("是否退出？", "维思课堂", MessageBoxButtons.OKCancel,MessageBoxIcon.Question))
            {
               
                    
                this.Close();
                Application.Exit();
            }
            
        }
        /// <summary>
        /// 更新连接状态提示信息
        /// </summary>
        private void UpdateCountStatus()
        {
            if(this.InvokeRequired)
            {
                Action ac = new Action(UpdateCountStatus);
                this.Invoke(ac);
            }
            else
            {
                this.labTotal.Text ="总人数："+ All.ToString();
                this.labCon.Text = "已连接："+Conn.ToString();
                this.labDis.Text = "未连接："+Disconn.ToString();
                ELogger.Trace(string.Format("总人数：{0}，已连接：{1}，未连接：{2}", All, Conn, Disconn));
            }
        }
        /// <summary>
        /// 更新笔连接列表的连接状态
        /// </summary>
        /// <param name="penSerial"></param>
        /// <param name="conn"></param>
        private void UpdatePenListStatus(string penSerial,bool conn=true)
        {
            if (this.InvokeRequired)
            {

                Action<string,bool> ac = new Action<string,bool>(UpdatePenListStatus);
                this.Invoke(ac, new object[] { penSerial, conn });
            }
            else
            {

                if(penItemList.ContainsKey(penSerial))
                {
                    PenItem pi = penItemList[penSerial];
                    if (conn)
                        pi.ChangePenStatus(PenStatus.Normal);
                    else
                        pi.ChangePenStatus(PenStatus.DisConnected);
                   
                }
               

            }
        }
        /// <summary>
        /// 将标签与学生信息关联
        /// </summary>
        /// <param name="penserial"></param>
        /// <param name="pageSerial"></param>
        /// <param name="nx"></param>
        /// <param name="ny"></param>
        private void MapPenserialToStudent(string penserial,string pageSerial,int nx,int ny)
        {
            if(!studentListDic.ContainsKey(penserial))
            {
                string name=Program.MTInfo.GetStudentName(pageSerial, nx, ny);
                if (!string.IsNullOrEmpty(name))
                    studentListDic[penserial] = name;
            }
        }
        /// <summary>
        /// 添加BindLabel
        /// </summary>
        /// <param name="penSerial"></param>
        private void AddBindLabel(string penSerial)
        {
            if (this.InvokeRequired)
            {
                Action<string> action = new Action<string>(AddBindLabel);
                this.Invoke(action, new object[] { penSerial });
            }
            else
            {
                BindLable bl = new BindLable(penSerial);
                statusWindows.Add(penSerial, bl);
                bl.OnMenuEvent += Bl_OnMenuEvent;
                bl.Margin = new Padding(20, 10, 20, 10);
                flpClient.Controls.Add(bl);
                bool exsiting = false;
                
                foreach (var item in flpPenlist.Controls)
                {
                    PenItem pi = (PenItem)item;
                    if(pi.PenSerial.Equals(penSerial))
                    {
                        pi.ChangePenStatus(PenStatus.Normal);
                        exsiting = true;
                        break;
                    }
                }
                if(!exsiting)
                {
                    PenItem pi = new PenItem();
                    pi.PenSerial = penSerial;
                    pi.NormalImage = Resources.pen_ico_link;
                    pi.DisableImage = Resources.pen_ico_fail;
                    pi.ChangePenStatus(PenStatus.Normal);
                    pi.DisconectedImage = Resources.pen_ico_fail;
                    pi.ClickPen += Pi_ClickPen;
                    flpPenlist.Controls.Add(pi);
                    penItemList.Add(penSerial, pi);
                }
                
            }
            
        }

        private void Pi_ClickPen(object sender, ClickPenEventArgs args)
        {
            
        }
        /// <summary>
        /// 更新绑定状态
        /// </summary>
        /// <param name="penSerial"></param>
        /// <param name="studentName"></param>
        private void UpdataBindLabelStatus(string penSerial,string studentName)
        {
            if(this.InvokeRequired)
            {
                Action<string, string> ac = new Action<string, string>(UpdataBindLabelStatus);
                this.Invoke(ac, new object[] { penSerial, studentName });
            }
            else
            {
                statusWindows[penSerial].BindStudent(studentName);
            }
        }
        /// <summary>
        /// 更新左侧笔列表名称
        /// </summary>
        /// <param name="pi"></param>
        /// <param name="penName"></param>
        private void UpdatePenListItemName(PenItem pi,string penName)
        {
            if (this.InvokeRequired)
            {
                Action<PenItem, string> ac = new Action<PenItem, string>(UpdatePenListItemName);
                this.Invoke(ac, new object[] { pi, penName });
            }
            else
            {
                pi.SetName(studentListDic[penName]);

            }
        }
        /// <summary>
        /// 删除已存在的笔
        /// </summary>
        /// <param name="penSerial"></param>
        private void RemoveBindPen(string penSerial)
        {
            if(this.InvokeRequired)
            {
                Action<string> ac = new Action<string>(RemoveBindPen);
                this.Invoke(ac, new object[] { penSerial });
            }
            else
            {
                //删除左侧
                if(penItemList.ContainsKey(penSerial))
                {
                    PenItem pi = penItemList[penSerial];
                    penItemList.Remove(penSerial);
                    flpPenlist.Controls.Remove(pi);
                }

                //删除右侧
                if (statusWindows.ContainsKey(penSerial))
                {
                    BindLable bl = statusWindows[penSerial];
                    statusWindows.Remove(penSerial);
                    flpClient.Controls.Remove(bl);
                }
                
                //删除记录列表
                if(studentListDic.ContainsKey(penSerial))
                    studentListDic.Remove(penSerial);
            }
            
        }
        /// <summary>
        /// 抬笔事件
        /// </summary>
        /// <param name="time"></param>
        /// <param name="penSerial"></param>
        /// <param name="penType"></param>
        public void DigitalPen_PenUp(ulong time, string penSerial, int penType)
        {

            if (statusWindows.ContainsKey(penSerial) == false)
            {
                AddBindLabel(penSerial);
            }
            if (studentListDic.ContainsKey(penSerial))
            {
                bool exist = false;
                string oldPenSerial = "";
                foreach (var item in penItemList)
                {
                    if(penSerial.Equals(item.Key)==false 
                        && item.Value.GetPenName().Equals(studentListDic[penSerial]))
                    {
                        oldPenSerial = item.Key;
                        exist = true;
                        break;
                    }
                }
                if(exist)
                {
                    if (DialogResult.OK == MessageBox.Show(string.Format("是否将学生【{0}】的点阵笔由\n【{1}】更换为【{2}】",
                        studentListDic[penSerial], oldPenSerial, penSerial),"维思课堂",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        ELogger.Trace(string.Format("更换学生【{0}】的点阵笔由【{1}】更换为【{2}】",
                        studentListDic[penSerial], oldPenSerial, penSerial));
                        RemoveBindPen(oldPenSerial);

                        UpdataBindLabelStatus(penSerial, studentListDic[penSerial]);
                        foreach (var item in flpPenlist.Controls)
                        {
                            PenItem pi = (PenItem)item;
                            if (pi.PenSerial.Equals(penSerial))
                            {
                                //pi.SetName(studentListDic[penSerial]);
                                UpdatePenListItemName(pi, penSerial);

                                break;
                            }
                        }
                    }
                    else
                    {
                        studentListDic.Remove(penSerial);
                    }

                }
                else
                { 
                    UpdataBindLabelStatus(penSerial, studentListDic[penSerial]);
                    foreach (var item in flpPenlist.Controls)
                    {
                        PenItem pi = (PenItem)item;
                        if (pi.PenSerial.Equals(penSerial))
                        {
                            UpdatePenListItemName(pi, penSerial);
                            break;
                        }
                    }
                }
                All = studentListDic.Count;
                UpdateCountStatus();
                UpdatePenListStatus(penSerial);
            }
        }
        /// <summary>
        /// 落笔事件
        /// </summary>
        /// <param name="time"></param>
        /// <param name="penSerial"></param>
        /// <param name="penType"></param>
        public void DigitalPen_PenDown(ulong time, string penSerial, int penType)
        {
            if (statusWindows.ContainsKey(penSerial) == false)
            {
                AddBindLabel(penSerial);
            }
            IsPenDown = true;

        }
        /// <summary>
        /// 笔坐标事件
        /// </summary>
        /// <param name="time"></param>
        /// <param name="penSerial"></param>
        /// <param name="penType"></param>
        /// <param name="pageSerial"></param>
        /// <param name="pageId"></param>
        /// <param name="cx"></param>
        /// <param name="cy"></param>
        /// <param name="force"></param>
        public void DigitalPen_PenCoordinate(ulong time, string penSerial, int penType, string pageSerial, ulong pageId, int cx, int cy, byte force)
        {
            if (statusWindows.ContainsKey(penSerial) == false)
            {
                AddBindLabel(penSerial);
            }
            if (IsPenDown)
            {
                IsPenDown = false;
                //改学生名字
                MapPenserialToStudent(penSerial, pageSerial, cx, cy);

            }
        }
        /// <summary>
        /// 笔断开
        /// </summary>
        /// <param name="time"></param>
        /// <param name="penSerial"></param>
        /// <param name="penType"></param>
        public void DigitalPen_PenDisconnect(ulong time, string penSerial, int penType)
        {
            ELogger.Trace(string.Format("{0} 断开连接",penSerial));
            if (statusWindows.ContainsKey(penSerial) == false)
            {
                AddBindLabel(penSerial);
               
            }
            UpdatePenListStatus(penSerial,false);
        }

        /// <summary>
        /// 笔连接
        /// </summary>
        /// <param name="time"></param>
        /// <param name="penSerial"></param>
        /// <param name="penType"></param>
        public void DigitalPen_PenConnected(ulong time, string penSerial, int penType)
        {
            ELogger.Trace(string.Format("{0} 建立连接",penSerial));
            if (statusWindows.ContainsKey(penSerial)==false)
            {
                ELogger.Trace(string.Format("{0} 建立连接，添加状态窗口", penSerial));
                AddBindLabel(penSerial);
            }
            UpdateCountStatus();
            UpdatePenListStatus(penSerial);
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            
            this.tlpBase.Visible = true;
            InitPrepare();

        }
        /// <summary>
        /// 最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
        /// <summary>
        /// 屏蔽回车和空格
        /// </summary>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Enter || keyData == Keys.Space)
                return false;
            return base.ProcessDialogKey(keyData);
        }
        /// <summary>
        /// 考试未检测到学生名单，绑定后返回考试或上课
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        
        private void btnBindAndBacktoScene_Click(object sender, EventArgs e)
        {
            if (studentListDic.Count == 0)
            {
                MessageBox.Show("学生尚未绑定！", "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ELogger.Trace("学生尚未绑定！");
                return;
            }
            Program.StudentInfo.ClearBindInfo();
            foreach (var item in studentListDic)
            {
                StudentCard sc = Program.MTInfo.GetStudentCardByName(item.Value);
                Program.StudentInfo.AddBandInfo(item.Key, sc);
            }
            Program.StudentInfo.Class = Program.MTInfo.MicroTestRoomInfo;
            if (FrmSwhich.SwhichFrm.GetSceneType() == SceneType.Scene_ClassPrepare)
            {
                FrmSwhich.SwhichFrm.SwichToScene(SceneType.Scene_Class);

            }
            else if (FrmSwhich.SwhichFrm.GetSceneType() == SceneType.Scene_ExamPrepare)
            {
                FrmSwhich.SwhichFrm.SwichToScene(SceneType.Scene_Exam);
            }
            this.Close();
        }

        private void pnlTop_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tlpBase_Paint(object sender, PaintEventArgs e)
        {

        }

        private void labBJ_Click(object sender, EventArgs e)
        {

        }

        private void flpClient_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pnlRightButton_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void pnlMain_Paint(object sender, PaintEventArgs e)
        {

        }

        private void flpMain_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pnlPenList_Paint(object sender, PaintEventArgs e)
        {

        }

        private void flpPenlist_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pnlBottomButton_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pnlStat_Paint(object sender, PaintEventArgs e)
        {

        }

        private void labDis_Click(object sender, EventArgs e)
        {

        }

        private void labCon_Click(object sender, EventArgs e)
        {

        }

        private void labTotal_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            ELogger.Trace("用户点击了关闭按钮！");
            if (DialogResult.OK == MessageBox.Show("是否退出？", "维思课堂", MessageBoxButtons.OKCancel,MessageBoxIcon.Question))
            {


                this.Close();
                Application.Exit();
            }
        }
        private void DisableButton(object btn)
        {
            if(this.InvokeRequired)
            {
                Action<object> ac = new Action<object>(DisableButton);
                this.Invoke(ac, new object[] { btn });
            }
            else
            {
                (btn as ImageButton).NormalImage = Properties.Resources.btn_upload_disabled;
                (btn as ImageButton).Enabled = false;
            }
        }
        

        
    }
    

}
